﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace GrayParrot.IOC
{
    public static class Factory
    {
        private static ObjectCache m_cache = MemoryCache.Default;

        private static IUnityContainer m_container = null;

        public static I Create<I>() where I : class
        {
            I retValue = null;

            I m_instance = (I)m_cache.Get(typeof(I).ToString());
            if (m_instance != null)
            {
                retValue = m_instance;
            }
            else
            {
                m_container = new UnityContainer();
                m_container.LoadConfiguration();

                retValue = m_container.Resolve<I>();

                // cache objects expires after 3 minutes...
                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(180.0);

                m_cache.Add(typeof(I).ToString(), retValue, policy);
            }

            return retValue;
        }

        public static I Create<I>(string name) where I : class
        {
            I retValue = null;

            I m_instance = (I)m_cache.Get(typeof(I).ToString());
            if (m_instance != null)
            {
                retValue = m_instance;
            }
            else
            {
                m_container = new UnityContainer();
                m_container.LoadConfiguration();

                retValue = m_container.Resolve<I>(name);

                // cache objects expires after 3 minutes...
                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(180.0);

                m_cache.Add(typeof(I).ToString(), retValue, policy);
            }

            return retValue;
        }
    }
}
